//
//  StoreConfigChildServiceViewController.swift
//  DSHCMerchant
//
//  Created by 罗德良 on 2018/4/18.
//  Copyright © 2018年 袋鼠好车. All rights reserved.
//

import UIKit
import Alamofire

class StoreConfigChildServiceViewController: BaseViewController {

    @IBOutlet var childserviceTableview: UITableView!
    var childServiceId = ""
    let childServiceCell = "childServiceCell"
    var childServices :[ServiceModel]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configView()
        requstChildServicesList(serviceId: childServiceId)
        baseSetNavRightButtonWithTitle("添加服务")
    }
    
    override func baseNavRightButtonPressed(_ button: UIButton) {
        let produceOrderView = ProduceOrderView.getProduceOrderPopView()
        produceOrderView.titleLabel.text = "添加服务"
        produceOrderView.priceTF.isHidden = true
        produceOrderView.remarksTF.isHidden = true
        produceOrderView.codeTF.placeholder = "请输入服务名称"
        produceOrderView.codeTF.keyboardType = UIKeyboardType.default
        produceOrderView.callBackBlock { (boolValue) in
            switch boolValue {
            case true:
                if (produceOrderView.codeTF.text == ""){
                    MBProgressHUD.alertShow(in: produceOrderView, message: "请填写服务后再提交", hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                                return
                }
                self.requestAddService(name: produceOrderView.codeTF.text!)
                bgWindow?.hidBackgroundWindow()
            case false:
                bgWindow?.hidBackgroundWindow()
            }
        }
        bgWindow = DSHCBcakgroundWindow.setupBackgroundWindowAndShow()
        bgWindow?.shake(toShow: produceOrderView)
     }
    func configView() -> Void {
        childserviceTableview.delegate = self
        childserviceTableview.dataSource = self
        childserviceTableview.separatorStyle = .none
        childserviceTableview.showsVerticalScrollIndicator = false
        childserviceTableview.backgroundColor = BaseColor.BackGroundColor
        childserviceTableview.register(UINib(nibName: "StoreConfigChildServiceTableViewCell", bundle: nil), forCellReuseIdentifier: childServiceCell)
    }
    
    //网络请求
    //店铺子服务列表
    func requstChildServicesList(serviceId:String) -> Void {
        
        Alamofire.request(getOneStoreConfigUrl, method:.post, parameters: ["id":serviceId,"sid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = BaseResponseOfModel<BaseArrayData<ServiceModel>>()
                    basemodel = BaseResponseOfModel.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        
                        self.childServices = basemodel.data?.data
                        print("数据请求成功")
                    self.childserviceTableview.reloadData()
                    case false:
                        print("数据错误")
                        
                    }
                    
                case false:
                    print(response.result.error!)
                }
        }
    }
    
    //删除
    func requestRemoveService(Id:String) -> Void {
        
        
        Alamofire.request(deleteStoreServiceUrl, method:.post, parameters:["id":Id,"sid":UserModel.shareUser.data?.storeId ?? String()])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        print("删除成功")
                        self.requstChildServicesList(serviceId: self.childServiceId)
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    //新增
    func requestAddService(name:String) -> Void {
        
        
        Alamofire.request(addStoreServiceUrl, method:.post, parameters:["name":name,"sid":UserModel.shareUser.data?.storeId ?? String(),"pid":childServiceId])
            .responseString { response in
                
                switch response.result.isSuccess {
                case true:
                    
                    var basemodel = DefaultData()
                    basemodel = DefaultData.deserialize(from: response.value)!
                    
                    switch basemodel.status! {
                    case true:
                        print("新增成功")
                        self.requstChildServicesList(serviceId: self.childServiceId)
                    case false:
                         MBProgressHUD.alertShow(in: self.view, message:basemodel.msg, hidenAfter: 0.8, mode: MBProgressHUDMode.text)
                    }
                    
                case false:
                    print(response.result.error!)
                }
                
        }
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension StoreConfigChildServiceViewController: UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.childServices?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.childServices![indexPath.item]
        let cell = tableView.dequeueReusableCell(withIdentifier: childServiceCell, for: indexPath) as! StoreConfigChildServiceTableViewCell
        cell.selectionStyle = .none
        cell.titleLabel.text = model.name
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ScaleHeight(40)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    //    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    //        return 10
    //    }
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        
        return UITableViewCellEditingStyle.delete
        
    }
    
    

    //在这里修改删除按钮的文字
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        
        return "删除"
        
    }
    
    
    
    //点击删除按钮的响应方法，在这里处理删除的逻辑
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let model = self.childServices![indexPath.item]
        if editingStyle == UITableViewCellEditingStyle.delete {
            
            requestRemoveService(Id:model.id)
//            self.dataList!.removeAtIndex(indexPath.row)
//
//            self.tableView!.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            
        }
        
    }
    
}
